const Router = require("koa-router");
const R = require("../app/R");
const { connectionMap } = require("../app/socket");
const onlineChatRouter = new Router({ prefix: "/onlineChat" });

onlineChatRouter.post("/connection", (ctx, next) => {
  let requestBody = ctx.request.body;
  console.log(requestBody);
  let {
    UserId: fromUserId,
    Nickname: fromNickname,
    AvatarUrl: fromAvatarUrl,
  } = requestBody.from; // 发送方
  let {
    UserId: toUserId,
    Nickname: toNickname,
    AvatarUrl: toAvatarUrl,
  } = requestBody.to; //接收方

  if (!connectionMap[fromUserId]) {
    connectionMap[fromUserId] = [];
  }
  if (!connectionMap[toUserId]) {
    connectionMap[toUserId] = [];
  }

  // 将“接收方”添加进“发送方”的连接列表
  if (
    connectionMap[fromUserId].findIndex((item) => item.UserId == toUserId) == -1
  ) {
    connectionMap[fromUserId].push({ ...requestBody.to });
  }
  console.log(connectionMap);
  ctx.body = new R();
});

onlineChatRouter.post("/close", (ctx, next) => {
  let requestBody = ctx.request.body;
  console.log(requestBody);
  let {
    UserId: fromUserId,
    Nickname: fromNickname,
    AvatarUrl: fromAvatarUrl,
  } = requestBody.from;
  let {
    UserId: toUserId,
    Nickname: toNickname,
    AvatarUrl: toAvatarUrl,
  } = requestBody.to;
  connectionMap[fromUserId] = connectionMap[fromUserId].filter(
    (item) => item.UserId != toUserId
  );
  console.log(connectionMap);
  ctx.body = new R();
});

onlineChatRouter.post("/connectionList", (ctx, next) => {
  let UserId = ctx.request.body.UserId;
  console.log(connectionMap);
  ctx.body = new R().setResult(connectionMap[UserId]);
});

module.exports = onlineChatRouter;
